package com.baiyang.server.tools;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.baiyang.server.annotation.NotNull;

/**
 *  判断实体类中被@NotNull注解注释的元素是否是为空
 * @author XVX
 */
public class SubjectNotNull {
	/**
	 * 判断model中的string成员变量是否都为空
	 * @param object
	 * @return
	 */
	public static boolean subjectIsNull(Object object) {
		if(object == null) {
			return true;
		}
		ArrayList<Field> fieldArr = deal(object.getClass());
		for (Field field : fieldArr) {
			try {
				if(field.get(object) instanceof String) {
					String str = (String) field.get(object);
					if(str != null && !"".equals(str)) {
						continue;
					}else {
						return true;
					}
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
				return true;
			}
		}
		return false;
	}
    /**
     * @param object
     * @return
     * 判断被注解声明的是否有是否为空
     */
    public static Map<String,String> subject(Object object){
        Map<String,String> result = new HashMap<>();
        ArrayList<Field> fields = deal(object.getClass());
        for (Field field : fields) {
            try {
                if(field.get(object) == null) {
                    result.put(field.getName(),field.getAnnotation(NotNull.class).value());
                }
                else if(field.get(object) instanceof String){
                    if(field.get(object).equals("")){
                        result.put(field.getName(),field.getAnnotation(NotNull.class).value());
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    private static Map<Class<? extends Object>, ArrayList<Field>> map = new ConcurrentHashMap<Class<? extends Object>,ArrayList<Field>>();
    private static ArrayList<Field> deal(Class<? extends Object> type) {
        if(map.containsKey(type)) {
            return map.get(type);
        }
        else {
            ArrayList<Field> list = new ArrayList<Field>();
            if(type.isAnnotationPresent(NotNull.class)) {
                Field[] fieldArr = type.getDeclaredFields();

                for (int i=0;i<fieldArr.length;i++){//遍历
                    //得到属性
                    Field field = fieldArr[i];
                    //打开私有访问
                    field.setAccessible(true);
                    if(field.isAnnotationPresent(NotNull.class)) {
                        list.add(field);
                    }
                }
            }
            map.put(type, list);
            return list;
        }
    }
}
